<template>
	<view class="chat-ai-input" @touchmove.stop.prevent>
		<!-- 分类区 -->
		<view class="types">
			
			<!-- <view :class="[checkedType==index?'types-item-active':'']" class="types-item" v-for="(item,index) in types"
				:key="index" @click="_change_type(item,index)">
				<image :src="checkedType==index?item.selectIcon:item.icon" mode=""></image>
				<text>{{item.name}}</text>
			</view> -->
		</view>
		<view class="chat">
			<view class="chat-ipt" v-if="checkedType == -1 || checkedType == 0 || checkedType == 3">
				<scroll-view class="height110" scroll-y>
					<textarea style="color:#000;padding-top:5px;" :maxlength="2000" v-model="innerVal"   @confirm="_confirm" @input="_onInput"
						:placeholder="checkedPlaceholder"></textarea>
				</scroll-view>
				
				<view class="chat-ipt-bottom">
					<view class="tools">
						<view v-if="checkedType==0" class="tools-item" @click="_upload_composition">
							<image class="tools-item-uploadimg" src="/static/icons/i_2.png" mode=""></image>
							<text>上传照片</text>
						</view>
						<view v-if="checkedType==3" class="tools-item" @click="_word_style">
							<text>{{fengge||'写作风格'}}</text>
							<u-icon class="u-m-l-10" color="#000000" name="arrow-down"></u-icon>
						</view>
						<view v-if="checkedType==3" class="tools-item" @click="_word_length">
							<text>{{changdu||'长度'}}</text>
							<u-icon class="u-m-l-10" color="#000000" name="arrow-down"></u-icon>
						</view>
						<view v-if="checkedType==3" class="tools-item" @click="_word_choice">
							<text>选词</text>
							<u-icon class="u-m-l-10" color="#000000" name="arrow-down"></u-icon>
						</view>
						<!-- <view v-if="checkedType==3" class="tools-item" @click="_word_type">
							<text>{{checkedTwoType}}</text>
							<u-icon class="u-m-l-10" color="#000000" name="arrow-down"></u-icon>
						</view> -->
					</view>
					<view class="send" @click="_send">
						<image v-if="!disabled" src="/static/icons/send.png" mode=""></image>
						<u-loading color="#ffffff" v-else mode="circle"></u-loading>
					</view>
				</view>
			</view>
			<!-- 拍照解题 -->
			<view v-else-if="checkedType == 1" class="chat-upload" @click="_upload_solve_problem">
				<image src="/static/icons/upload.png" mode=""></image>
				<text>拍照上传</text>
			</view>
			<!-- 口语练习 -->
			<view @touchstart="onTouchStart" @touchend="onTouchEnd" @touchmove="onTouchMove" v-else-if="checkedType == 2"
				class="chat-audio">
				<image src="/static/icons/audio.png" mode=""></image>
				<text >{{ recording ? '松手结束' : '长按说话' }}</text>
			</view>
		</view>
	</view>

	<view v-if="recording" class="recording-shadow">
		<view class="recording-shadow-tip">
			<text v-if="moveY < -40">松手取消</text>
			<text v-else>{{duration}}″</text>
		</view>
	</view>
</template>

<script setup>
	import {
		reactive,
		ref,
		onMounted,
		defineProps,
		computed
	} from 'vue'

	import {
		aiUpload
	} from "@/api/ai.js"
	
	import config from "@/config/index.js"

	const props = defineProps({
		changdu:{
			type: [Number,String],
			default:''
		},
		fengge:{
			type: [Number,String],
			default:''
		},
		type:{
			type: [Number,String],
			default: -1
		},
		textmodelValue:{
			type: String,
			default: "11111"
		},
		types: {
			type: Array,
			default: () => []
		},
		checkedType: {
			type: [Number,String],
			default: -1
		},
		modelValue: {
			type: String,
			default: ""
		},
		disabled: {
			type: Boolean,
			default: false
		},
		checkedTwoType: {
			type: String,
			default: "选择类型"
		},
		checkedTwoTypeId: {
			type: Number,
			default: -1
		}
	})
	const emits = defineEmits(['update:modelValue', 'update:checkedType', 'update:checkedTwoType','update:checkedTwoTypeId', 'send', 'checked',
		'wordChoice', 'wordType', 'wordStyle', 'wordLength'
	])
	 let checkedPlaceholder = ref("请输入你的问题")
	
	
	
	const innerVal = computed({
		get: () =>{
			return  props.modelValue
		},
		set: val =>{
			 emits('update:modelValue', val)
		}
	})
	
	const setinnerVal = (str) =>{
		emits('update:modelValue', str)
	}
	 defineExpose({
	   setinnerVal
	 })
	const recording = ref(false) // 是否正在录
	const duration = ref(0) // 录音时长 s
	const tempFilePath = ref('') // 最终 mp3 文件路径
	const moveY = ref(0) // 手指上移距离
	let timer = null // 计时器
	let startY = 0 // 按下的 y 坐标

	/* ---------- 微信小程序 ---------- */
	let wxRec = ref(null)
	const recorderManager = ref(null);

	/* ---------- H5 录音 ---------- */
	let mediaRec = ref(null)
	let chunks = []
	let h5Stream = null

	function onTouchStart(e) {
		if (recording.value) return
		recording.value = true
		duration.value = 0
		tempFilePath.value = ''
		startY = e.touches[0].pageY
		moveY.value = 0

		/* 计时器 */
		timer = setInterval(() => {
			duration.value++
		}, 1000)

		/* 平台各自开始 */
		// #ifndef H5
		recorderManager.value.start({
			format: "mp3",
			duration: 60000
		})
		// #endif
		// #ifdef H5
		navigator.mediaDevices.getUserMedia({
				audio: true
			})
			.then(stream => {
				h5Stream = stream
				mediaRec.value = new MediaRecorder(stream, {
					mimeType: 'audio/mp3'
				})
				chunks = []
				mediaRec.value.ondataavailable = e => chunks.push(e.data)
				mediaRec.value.onstop = () => {
					const blob = new Blob(chunks, {
						type: 'audio/mp3'
					})
					tempFilePath.value = URL.createObjectURL(blob) // H5 本地 blob url
					uni.showToast({duration: 2000,
						title: tempFilePath.value,
						icon: "none"
					})
					stream.getTracks().forEach(t => t.stop())
				}
				mediaRec.value.start()
			})
			.catch(() => uni.showToast({duration: 2000,
				title: '请允许麦克风',
				icon: 'none'
			}))
		// #endif
	}

	/* 手指移动：计算是否上滑 */
	function onTouchMove(e) {
		if (!recording.value) return
		moveY.value = e.touches[0].pageY - startY
	}

	/* 松手处理 */
	function onTouchEnd() {
		if (!recording.value) return
		recording.value = false
		clearInterval(timer)

		/* 上滑取消 */
		if (moveY.value < -40) {
			// #ifndef H5
			recorderManager.value.stop()
			// #endif
			// #ifdef H5
			if (mediaRec.value) mediaRec.value.stop()
			// #endif
			tempFilePath.value = ''
			uni.showToast({duration: 2000,
				title: '已取消',
				icon: 'none'
			})
			return
		}

		/* 正常结束 */
		// #ifndef H5
		recorderManager.value.stop()
		// #endif

		// #ifdef H5
			if (mediaRec.value) {
				mediaRec.value.stop()
			}
		// #endif
	}

	const _change_type = (item, index) => {
		if (index == props.checkedType) {
			return
		}
		// 判断是否在响应中，禁止点击其他模式
		if (props.disabled) {
			emits('checked', item)
			return
		}
		// emits('update:checkedType', index)
		// emits('checked', item)
		// checkedPlaceholder.value = item.placeholder
	}
	const _upload_solve_problem = () => {
		uni.chooseImage({
			count: 1,
			sourceType: ["camera"],
			success: (result) => {
				aiUpload(result.tempFilePaths[0]).then((response) => {
					emits('send', {
						messageType: config.MESSAGE_TYPE_IMAGE,
						content: response.data.url,
						url: response.data.url,
						isocr: true
					})
				})
			},
			fail: (error) => {
				uni.showToast({duration: 2000,
					title: error.message ?? "你取消了",
					icon: "none"
				})
			}
		})
	}
	const _upload_composition = () => {
		uni.chooseImage({
			count: 1,
			success: (result) => {
				aiUpload(result.tempFilePaths[0]).then((response) => {
					emits('send', {
						messageType: config.MESSAGE_TYPE_IMAGE,
						content: response.data.url,
						url: response.data.url,
						isocr: true
					})
				})
			},
			fail: (error) => {
				uni.showToast({duration: 2000,
					title: error.message ?? "你取消了",
					icon: "none"
				})
			}
		})
	}
	const _onInput = (evt) => {
		emits('update:modelValue', evt.detail.value)
	}

	const _confirm = (evt) => {
		// emits('send', props.modelValue)
		_send()
	}

	const _send = () => {
		switch (+props.checkedType){
			case 0:
				emits('send', {
					messageType: config.MESSAGE_TYPE_TEXT,
					content: props.modelValue,
					url: "",
					isocr: false,
					vocabularyType: 99,
				})
				break;
			case 3:
				let val = props.modelValue
				emits('send', {
					messageType: config.MESSAGE_TYPE_WORD,
					content: props.modelValue,
					url: "",
					isocr: false,
					vocabularyType: props.checkedTwoTypeId,
					targetWord: val
				})
				break;
			default:
				emits('send', {
					messageType: config.MESSAGE_TYPE_TEXT,
					content: props.modelValue,
					url: "",
					isocr: false,
					vocabularyType: 99,
				})
				break;
		}
	}

	const _word_choice = () => {
		emits('wordChoice')
	}
	const _word_style = () => {
		emits('wordStyle')
	}
	
	const _word_length = () => {
		emits('wordLength')
	}
	const _word_type = () => {
		emits('wordType')
	}

	onMounted(() => {
			
		// #ifndef H5
			recorderManager.value = uni.getRecorderManager();
			recorderManager.value.onStop((res) => {
				tempFilePath.value = res.tempFilePath
				aiUpload(res.tempFilePath).then((response) => {
					emits('send', {
						messageType: config.MESSAGE_TYPE_AUDIO,
						content: response.data.url,
						url: response.data.url,
						isocr: true
					})
				})
			})
		// #endif
		
		
		if(props.type!=4){
			setTimeout(()=>{
				emits('update:checkedType', props.type)
				emits('checked', props.types[props.type])
				// checkedPlaceholder.value = props.types[props.type].placeholder
			},1000)
		}
	})

	defineOptions({
		name: "chat-ai-input"
	})
</script>

<style lang="scss" scoped>
	.chat-ai-input {
		display: flex;
		flex-direction: column;
	}

	.types {
		display: flex;
		align-items: center;
		margin: 20rpx;

		.types-item {
			border: 1rpx solid rgba(19, 28, 37, 0.5);
			border-radius: 20rpx 20rpx 20rpx 20rpx;
			height: 56rpx;
			display: flex;
			align-items: center;
			justify-content: center;
			width: 172rpx;
			margin-right: 20rpx;

			image {
				width: 36rpx;
				height: 36rpx;
			}

			text {
				font-weight: 400;
				font-size: 24rpx;
				color: #000000;
				line-height: 34rpx;
			}
		}

		.types-item-active {
			width: 172rpx;
			height: 56rpx;
			background: rgba(255, 46, 83, 0.1);
			border-radius: 20rpx 20rpx 20rpx 20rpx;
			display: flex;
			align-items: center;
			justify-content: center;
			border: none;

			text {
				font-weight: 400;
				font-size: 24rpx;
				color: #FD2F55;
				line-height: 34rpx;
			}
		}
	}

	.chat {
		// box-shadow: 0rpx -4rpx 30rpx 0rpx rgba(0, 0, 0, 0.1);
		box-shadow: 0 -6rpx 12rpx -8rpx rgba(0, 0, 0, 0.1);
		background: #FFFFFF;
		border-radius: 50rpx 50rpx 0rpx 0rpx;
		// height: 320rpx;
		padding: 30rpx;

		.chat-ipt {
			background: #F9F9F9;
			border-radius: 20rpx 20rpx 20rpx 20rpx;
			display: flex;
			flex-direction: column;

			textarea {
				padding: 20rpx 20rpx 0 20rpx;
				font-weight: 400;
				font-size: 28rpx;
				color: rgba(19, 28, 37, 0.5);
				line-height: 39rpx;
				height: 120rpx;
			}

			.chat-ipt-bottom {
				padding: 20rpx;
				display: flex;
				align-items: center;
				justify-content: space-between;

				.tools {
					display: flex;
					align-items: center;

					.tools-item {
						display: flex;
						align-items: center;
						margin-right: 15rpx;
						height: 46rpx;
						border-radius: 10rpx 10rpx 10rpx 10rpx;
						border: 1rpx solid rgba(19, 28, 37, 0.5);
						padding: 0 10rpx;

						.tools-item-uploadimg {
							width: 36rpx;
							height: 36rpx;
						}

						text {
							font-weight: 400;
							font-size: 24rpx;
							color: #000000;
							line-height: 34rpx;
						}
					}
				}

				.send {
					width: 56rpx;
					height: 56rpx;
					background-color: #FD2F55;
					border-radius: 50%;
					display: flex;
					justify-content: center;
					align-items: center;

					image {
						width: 56rpx;
						height: 56rpx;
					}
				}
			}
		}

		.chat-upload {
			height: 100rpx;
			background-color: #FD2F55;
			border-radius: 20rpx 20rpx 20rpx 20rpx;
			display: flex;
			align-items: center;
			justify-content: center;

			image {
				width: 58rpx;
				height: 58rpx;
			}

			text {
				font-weight: 500;
				font-size: 36rpx;
				color: #fff;
				line-height: 50rpx;
				margin-left: 10rpx;
			}
		}

		.chat-audio {
			height: 100rpx;
			background: #FD2F55;
			border-radius: 20rpx 20rpx 20rpx 20rpx;
			display: flex;
			align-items: center;
			justify-content: center;

			image {
				width: 58rpx;
				height: 58rpx;
			}

			text {
				font-weight: 500;
				font-size: 36rpx;
				color: #fff;
				line-height: 50rpx;
				margin-left: 10rpx;
			}
		}
	}

	.recording-shadow {
		position: absolute;
		top: 300rpx;
		width: 100%;
		display: flex;
		justify-content: center;

		.recording-shadow-tip {
			width: 200rpx;
			height: 60rpx;
			display: flex;
			justify-content: center;
			align-items: center;
			background-color: rgba(0, 0, 0, 0.4);
			color: #fff;
			border-radius: 10rpx;
		}
	}
</style>